import { Injectable } from '@angular/core';
import {Actions, ofType, Effect} from '@ngrx/effects';
import { Observable, of , pipe} from 'rxjs';
import { Router} from '@angular/router';
import * as actions from '../actions/auth.action';
import {
    LoginAction,
    RegisterAction
} from '../actions/auth.action';
import { Action } from '@ngrx/store';
import {StoreRouterConnectingModule} from '@ngrx/router-store';
import { AuthService } from '../services/auth.service';
import { switchMap, map, catchError , tap} from 'rxjs/operators';
import { User } from '../domain';
@Injectable()
export class AuthEffects {
    @Effect()
    login$: Observable<Action> = this.actions$.pipe(
        ofType(actions.ActionTypes.LOGIN),
        map( (a: LoginAction) => a.payload),
        switchMap(({email, password}) =>
            this.authService.login(email, password).pipe(
                    map(auth => new actions.LoginSuccessAction(auth)),
                    catchError(err => of(new actions.LoginFailAction(err)))
            ))
    );
    @Effect()
    register$: Observable<Action> = this.actions$.pipe(
        ofType(actions.ActionTypes.REGISTER),
        map( (a: RegisterAction) => a.payload),
        switchMap(
            (user: User) => this.authService.register(user).pipe(
                map(auth => new actions.RegisterSuccessAction(auth)),
                catchError(err => of(new actions.RegisterFailAction(err)))
            ))
    );
    @Effect({dispatch:  false})
    logout$ = this.actions$.pipe(
        ofType(actions.ActionTypes.LOGOUT),
        tap((a) =>   this.router.navigate(['/login']))
    );
    @Effect({ dispatch:  false })
    loginAndNavigate$ = this.actions$.pipe(
        ofType(actions.ActionTypes.LOGIN_SUCCESS),
        tap( _ =>   this.router.navigate(['projects']))
    );
    @Effect({ dispatch:  false })
    registerAndNavigate$ = this.actions$.pipe(
        ofType(actions.ActionTypes.REGISTER_SUCCESS),
        tap( _ =>   this.router.navigate(['projects']))
    );
    constructor(
        public actions$:  Actions,
        public authService:  AuthService,
        public router:  Router
      ) {}
}
